import Handler from "./Handler";
import i from "./SystemDataSys"
import r from "./frameworkManager"
import n from "./SdkHelper"
import l from "./Service"
import s from "./EngineUtil"

const { ccclass, property } = cc._decorator;

@ccclass
export default class HttpUtil {
    private static _postQueue: { url: string, reqData: any, handler: any }[] = [];
    private static _inRequesting: boolean = false;

    public static queuePost(url: string, reqData: any, handler: any) {
        if (!handler || handler.enterQueue()) {
            this._postQueue.push({
                url: url,
                reqData: reqData,
                handler: handler
            });
            if (!this._inRequesting) {
                this._inRequesting = true;
                this._Post(url, reqData, handler);
            }
        } else {
            this._Post(url, reqData, handler);
        }
    }

    public static queuePostCallback(url, responseCode: number, responseData: any, callback: any) {
        var queueItem = this._postQueue[0];
        var requestUrl = queueItem.url;
        var requestHandler = queueItem.handler;

        if (i.online_release && s.getRandomNum(1, 100) <= 5) {
            var responseTime = Date.now() - url;
            n.reportData("http_monitor", {
                request_path: requestUrl,
                response_code: responseCode,
                response_time: responseTime
            });
        }

        if (!responseData && requestHandler && requestHandler.needRetry()) {
            this._postQueue[0].url = l.genRequestUrl(requestHandler.getRequestType());
            r.httpErr(callback, function () {
                return this.requestQueueHead();
            });
        } else {
            if (responseData) {
                requestHandler.success(callback);
            } else {
                requestHandler.fail(callback);
            }

            this._postQueue.shift();
            this.requestQueueHead();
        }
    }

    private static requestQueueHead() {
        if (this._postQueue && this._postQueue.length) {
            var queueItem = this._postQueue[0];
            if (queueItem && queueItem.url) {
                this._Post(queueItem.url, queueItem.reqData, queueItem.handler);
            } else {
                this.requestQueueHead();
            }
        } else {
            this._inRequesting = false;
        }
    }

    private static _Post(url: string, reqData: any, handler) {
        var responseCode: number = 9999;
        var startTime: number = Date.now();

        var xhr = new XMLHttpRequest();
        var handleResult = function (success: boolean, result: any) {
            handler.success(result);
            if (handler && handler.enterQueue()) {
                // this.queuePostCallback(startTime, responseCode, success, result);
            } else {
                if (success) {
                    handler.success(result);
                } else {
                    handler.fail(result);
                }
            }
        };

        var handleStateChange = function () {
            handleResult(false, {
                code: -1,
                message: "xhr.status" + xhr.status,
                http_status: xhr.status
            });
            if (xhr.readyState === 4) {
                responseCode = xhr.status;

                if (xhr.status >= 200 && xhr.status < 400) {
                    var responseText = xhr.responseText;

                    if (responseText) {
                        var responseData = JSON.parse(responseText);

                        if (responseData.ecp !== null && responseData.ecp !== undefined) {
                            responseData = n.getAesDncrypData(responseData.data);
                            console.log("解密结果", JSON.stringify(responseData));
                        }

                        if (url.includes(i.server_test_url) || url.includes(i.server_release_url)) {
                            var code = responseData.code;

                            if (code === -1 || code === -1000) {
                                handleResult(false, responseData);
                                return;
                            }

                            handleResult(true, responseData);
                            return;
                        }

                        handleResult(true, responseData);
                    } else {
                        console.log("返回数据不存在");
                        handleResult(false, {
                            code: -1,
                            message: "返回数据不存在",
                            http_status: xhr.status
                        });
                    }
                } else {
                    console.log("请求失败");
                    handleResult(false, {
                        code: -1,
                        message: "xhr.status" + xhr.status,
                        http_status: xhr.status
                    });
                }
            }
        };

        xhr.onreadystatechange = handleStateChange.bind(this);
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-type", "multipart/form-data;boundary=AaB03x");
        // n.setXhrCookie(xhr);

        // xhr.send(reqData.arrayBuffer());

        xhr.addEventListener("abort", function () {
            cc.log("testlogin abort");
            handleResult(false, {
                code: -1,
                message: "onXhr.abort",
                http_status: xhr.status
            });
        });

        xhr.addEventListener("error", function () {
            cc.log("testlogin error");
            handleResult(false, {
                code: -1,
                message: "onXhr.error",
                http_status: xhr.status
            });
        });

        xhr.addEventListener("timeout", function () {
            cc.log("testlogin timeout");
            handleResult(false, {
                code: -1,
                message: "onXhr.timeout",
                http_status: xhr.status
            });
        });
    }
}